<script setup>
import { ref, computed } from 'vue'
import { useMessage } from 'naive-ui'
import { useMainStore } from '../pinia.js'

const message = useMessage()
const mainStore = useMainStore()

// 界面步骤控制
const currentStep = ref(0)
const steps = [
  { title: '基本信息', description: '输入Object No、Object Type和Product Line Code' },
  { title: '获取字段', description: '根据基本信息获取可更新的字段' },
  { title: '填写字段', description: '填写字段值并提交更新' }
]

// DFF API测试相关状态
const dffTestLoading = ref(false)
const fieldsLoading = ref(false)
const dffTestFormRef = ref(null)

// 基本信息表单
const basicInfo = ref({
  objectNo: '',
  objectType: 'order',
  productLineCode: ''
})

// 动态获取的字段数据
const availableFields = ref({
  customerFields: {},
  serviceFields: {},
  dffFields: {},
  dffList: []
})

// 用户填写的字段值
const fieldValues = ref({
  customerFields: {},
  serviceFields: {},
  dffFields: {},
  dffList: []
})

// 是否已获取字段
const fieldsLoaded = ref(false)

// 表单验证规则
const basicInfoRules = {
  objectNo: [
    {
      required: true,
      message: '请输入Object No',
      trigger: ['input', 'blur']
    }
  ],
  objectType: [
    {
      required: true,
      message: '请选择Object Type',
      trigger: ['change', 'blur']
    }
  ],
  productLineCode: [
    {
      required: true,
      message: '请输入Product Line Code',
      trigger: ['input', 'blur']
    }
  ]
}

// 获取可更新字段
const fetchAvailableFields = async () => {
  try {
    // 先进行基本信息验证
    await dffTestFormRef.value?.validate()
    
    fieldsLoading.value = true
    
    // 调用查询DFF模板API
    const response = await fetch('/api/file/query-dff-template', {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
        'Authorization': `Bearer ${mainStore.authToken}`
      },
      body: JSON.stringify({
        objectType: basicInfo.value.objectType === 'order' ? 'Order' : 'Enquiry',
        objectNo: basicInfo.value.objectNo,
        productLineCode: basicInfo.value.productLineCode
      })
    })
    
    const result = await response.json()
    
    if (result.success) {
      // 处理返回的字段数据
      const templateData = result.data
      
      // 初始化可用字段
      availableFields.value = {
        customerFields: {
          'ApplicantName(In Chinese)': '',
          'PayerName(In Chinese)': '',
          'ApplicantContactPersonName': '',
          'PayerContactPersonName': '',
          'ApplicantContactPersonEmail': '',
          'PayerContactPersonEmail': '',
          'ApplicantName(In English)': '',
          'PayerName(In English)': '',
          'ManufacturerName(In English)': ''
        },
        serviceFields: {
          'SoftCopy Deliver To': '',
          'Report Language': '',
          'Service Type': '',
          'Invoice Deliver Way': '',
          'Invoice Deliver To': '',
          'Return Sample To': '',
          'Return Residue Sample Flag': '',
          'Return Residue Sample Remark': '',
          'Return Tested Sample Flag': '',
          'Same As Applicant': '',
          'Report Header (English)': '',
          'Report Header (Chinese)': '',
          'Report Address (English)': '',
          'Report Address (Chinese)': ''
        },
        dffFields: {},
        dffList: []
      }
      
      // 处理DFF字段数据
      if (templateData.productDffResponse && Array.isArray(templateData.productDffResponse)) {
        templateData.productDffResponse.forEach(item => {
          if (item.fieldName) {
            availableFields.value.dffFields[item.fieldName] = ''
          }
        })
      }
      
      if (templateData.samplesDffResponse && Array.isArray(templateData.samplesDffResponse)) {
        templateData.samplesDffResponse.forEach(item => {
          if (item.fieldName) {
            availableFields.value.dffFields[item.fieldName] = ''
          }
        })
      }
      
      // 初始化DFF列表结构
      availableFields.value.dffList = [
        {
          languageId: 1,
          product: {
            productDescription: '',
            lotNo: '',
            refCode1: ''
          },
          productSamples: [
            {
              sampleID: '',
              otherSampleInformation: '',
              productDescription: ''
            }
          ]
        }
      ]
      
      // 初始化字段值
      fieldValues.value = JSON.parse(JSON.stringify(availableFields.value))
      
      fieldsLoaded.value = true
      currentStep.value = 2 // 跳转到填写字段步骤
      
      message.success('字段获取成功！请填写需要更新的字段值')
    } else {
      message.error(result.message || '获取字段失败')
    }
  } catch (error) {
    console.error('获取字段失败:', error)
    message.error('获取字段失败')
  } finally {
    fieldsLoading.value = false
  }
}

// 提交DFF更新
const submitDffUpdate = async () => {
  try {
    dffTestLoading.value = true
    
    // 检查SGS Token
    if (!mainStore.sgsToken) {
      message.error('缺少SGS认证token，请重新登录')
      return
    }
    
    // 过滤出有值的字段
    const filterEmptyFields = (fields) => {
      const filtered = {}
      Object.entries(fields).forEach(([key, value]) => {
        if (value && value.toString().trim()) {
          filtered[key] = value
        }
      })
      return filtered
    }
    
    // 过滤DFF列表，只保留有内容的项目
    const filterDffList = (dffList) => {
      return dffList.filter(item => {
        // 检查是否有任何字段被填写
        const hasProductData = item.product.productDescription?.trim() || 
                              item.product.lotNo?.trim() || 
                              item.product.refCode1?.trim()
        
        const hasSampleData = item.productSamples.some(sample => 
          sample.sampleID?.trim() || 
          sample.otherSampleInformation?.trim() || 
          sample.productDescription?.trim()
        )
        
        return item.languageId || hasProductData || hasSampleData
      }).map(item => ({
        ...item,
        productSamples: item.productSamples.filter(sample => 
          sample.sampleID?.trim() || 
          sample.otherSampleInformation?.trim() || 
          sample.productDescription?.trim()
        )
      }))
    }
    
    // 构建提交数据，只包含有值的字段
    const submitData = {
      objectNo: basicInfo.value.objectNo,
      objectType: basicInfo.value.objectType,
      productLineCode: basicInfo.value.productLineCode
    }
    
    // 只添加有值的字段组
    const filteredCustomerFields = filterEmptyFields(fieldValues.value.customerFields)
    const filteredServiceFields = filterEmptyFields(fieldValues.value.serviceFields)
    const filteredDffFields = filterEmptyFields(fieldValues.value.dffFields)
    const filteredDffList = filterDffList(fieldValues.value.dffList)
    
    if (Object.keys(filteredCustomerFields).length > 0) {
      submitData.customerFields = filteredCustomerFields
    }
    
    if (Object.keys(filteredServiceFields).length > 0) {
      submitData.serviceFields = filteredServiceFields
    }
    
    if (Object.keys(filteredDffFields).length > 0) {
      submitData.dffFields = filteredDffFields
    }
    
    if (filteredDffList.length > 0) {
      submitData.dffList = filteredDffList
    }
    
    // 检查是否有数据需要提交
    if (!submitData.customerFields && !submitData.serviceFields && 
        !submitData.dffFields && !submitData.dffList) {
      message.warning('请至少填写一个字段后再提交')
      return
    }
    
    console.log('提交数据:', submitData)
    
    // 验证必填字段
    if (!submitData.objectNo || !submitData.objectNo.trim()) {
      message.error('Object No 是必填字段，请填写订单号')
      console.log('验证失败: Object No 为空', submitData.objectNo)
      return
    }
    
    if (!submitData.productLineCode || !submitData.productLineCode.trim()) {
      message.error('Product Line Code 是必填字段，请填写产品线代码')
      console.log('验证失败: Product Line Code 为空', submitData.productLineCode)
      return
    }
    
    // 验证DFF必填项
    if (submitData.dffList && submitData.dffList.length > 0) {
      for (let i = 0; i < submitData.dffList.length; i++) {
        const dff = submitData.dffList[i]
        
        // 验证languageId
        if (!dff.languageId) {
          message.error(`DFF项目 ${i + 1} 的 Language ID 是必填字段`)
          console.log(`验证失败: DFF项目 ${i + 1} 的 languageId 为空`, dff.languageId)
          return
        }
        
        // 验证productSamples中的sampleID
        if (dff.productSamples && dff.productSamples.length > 0) {
          for (let j = 0; j < dff.productSamples.length; j++) {
            const sample = dff.productSamples[j]
            if (!sample.sampleID || !sample.sampleID.trim()) {
              message.error(`DFF项目 ${i + 1} 的样品 ${j + 1} 的 Sample ID 是必填字段`)
              console.log(`验证失败: DFF项目 ${i + 1} 样品 ${j + 1} 的 sampleID 为空`, sample.sampleID)
              return
            }
          }
        }
      }
    }
    
    // 验证Service字段中的所有必填contactsType
    const serviceFields = submitData.serviceFields || {}
    
    // 验证Invoice Deliver To
    if (!serviceFields['Invoice Deliver To'] || !serviceFields['Invoice Deliver To'].trim()) {
      message.error('Invoice Deliver To 是必填字段，请填写发票交付方式')
      console.log('验证失败: Invoice Deliver To 为空', serviceFields['Invoice Deliver To'])
      return
    }
    
    // 验证SoftCopy Deliver To
    if (!serviceFields['SoftCopy Deliver To'] || !serviceFields['SoftCopy Deliver To'].trim()) {
      message.error('SoftCopy Deliver To 是必填字段，请填写软拷贝交付方式')
      console.log('验证失败: SoftCopy Deliver To 为空', serviceFields['SoftCopy Deliver To'])
      return
    }
    
    // 验证Return Sample To
    if (!serviceFields['Return Sample To'] || !serviceFields['Return Sample To'].trim()) {
      message.error('Return Sample To 是必填字段，请填写样品退回方式')
      console.log('验证失败: Return Sample To 为空', serviceFields['Return Sample To'])
      return
    }

    console.log('必填字段验证通过:', {
      objectNo: submitData.objectNo,
      productLineCode: submitData.productLineCode,
      objectType: submitData.objectType,
      dffCount: submitData.dffList?.length || 0,
      invoiceDeliverTo: serviceFields['Invoice Deliver To'],
      softCopyDeliverTo: serviceFields['SoftCopy Deliver To'],
      returnSampleTo: serviceFields['Return Sample To']
    })
    
    // 构建SGS GPO API请求数据格式
    const requestData = {
      objectNo: submitData.objectNo.trim(),
      objectType: submitData.objectType || 'order',
      productLineCode: submitData.productLineCode.trim()
    }
    
    // 处理customerFields - 构建applicant, payer, manufacturer
    const customerFields = submitData.customerFields || {}
    
    // 确保applicant始终存在（必填字段）
    requestData.applicant = {
      contactName: customerFields['ApplicantContactPersonName'] || 'Test Contact',
      email: customerFields['ApplicantEmail'] || 'test@example.com'
    }
    
    // 可选字段：payer和manufacturer
    if (customerFields['PayerContactPersonName'] || customerFields['PayerEmail']) {
      requestData.payer = {
        contactName: customerFields['PayerContactPersonName'] || '',
        email: customerFields['PayerEmail'] || ''
      }
    }
    
    if (customerFields['ManufacturerName(In English)']) {
      requestData.manufacturer = {
        customerNameEn: customerFields['ManufacturerName(In English)']
      }
    }
    
    // 处理serviceRequirement - 按照文档要求包含完整的联系信息
    requestData.serviceRequirement = {
      contactInfos: [
        {
          contactsType: "invoiceDeliverTo",
          deliverOthers: serviceFields['Invoice Deliver To'] || "invoice@example.com",
          deliverTo: ["applicant", "buyer"]
        },
        {
          contactsType: "softCopyDeliverTo", 
          deliverOthers: serviceFields['SoftCopy Deliver To'] || "softcopy@example.com",
          deliverTo: ["applicant", "buyer"]
        },
        {
          contactsType: "returnSampleTo",
          deliverOthers: serviceFields['Return Sample To'] || "return@example.com", 
          deliverTo: ["applicant", "buyer"]
        }
      ],
      invoiceDeliverWay: "Express-Freight Prepaid",
      returnResidueSampleFlag: "0",
      returnTestedSampleFlag: "1"
    }
    
    // 添加必填的reportInfo字段
    requestData.reportInfo = {
      sameAsApplicant: 1, // 1表示与申请人相同
      reportLanguage: "1" // 1表示英文
    }
    
    // 处理dffList - 确保lotNo和refCode1不为空字符串
    if (submitData.dffList && submitData.dffList.length > 0) {
      requestData.dffList = submitData.dffList.map(dff => ({
        ...dff,
        languageId: dff.languageId || 1, // 确保languageId存在且不为空
        product: {
          ...dff.product,
          // 为空字符串提供默认值
          lotNo: dff.product.lotNo && dff.product.lotNo.trim() ? dff.product.lotNo : 'N/A',
          refCode1: dff.product.refCode1 && dff.product.refCode1.trim() ? dff.product.refCode1 : 'N/A',
          productDescription: dff.product.productDescription || 'Default Product'
        },
        productSamples: dff.productSamples && dff.productSamples.length > 0 ? 
          dff.productSamples.map(sample => ({
            ...sample,
            sampleID: sample.sampleID && sample.sampleID.trim() ? sample.sampleID : 'A', // 确保sampleID存在且不为空
            productDescription: sample.productDescription && sample.productDescription.trim() ? 
              sample.productDescription : (dff.product.productDescription || 'Default Sample') // 为空的productDescription提供默认值
          })) : 
          [{ sampleID: 'A', productDescription: 'Default Sample' }] // 提供默认样品
      }))
    } else {
      // 如果没有DFF数据，提供一个最小的默认DFF
      requestData.dffList = [
        {
          languageId: 1,
          product: {
            productDescription: "Test Product",
            lotNo: "N/A",
            refCode1: "N/A"
          },
          productSamples: [
            {
              sampleID: "A",
              productDescription: "Test Sample"
            }
          ]
        }
      ]
    }
    
    // 调用SGS GPO API更新DFF
    const gpoApiUrl = '/gpo-api/ai/tool/update'
    
    console.log('SGS API请求数据:', JSON.stringify(requestData, null, 2))
    console.log('请求URL:', gpoApiUrl)
    console.log('请求头:', {
      'Content-Type': 'application/json',
      'Sgstoken': mainStore.sgsToken ? '***已设置***' : '未设置',
      'Productlinecode': submitData.productLineCode
    })
    
    // 验证关键字段
    console.log('关键字段验证:')
    console.log('- objectNo:', requestData.objectNo)
    console.log('- objectType:', requestData.objectType)
    console.log('- productLineCode:', requestData.productLineCode)
    console.log('- applicant:', requestData.applicant)
    console.log('- dffList长度:', requestData.dffList?.length)
    if (requestData.dffList && requestData.dffList.length > 0) {
      requestData.dffList.forEach((dff, index) => {
        console.log(`- dff[${index}] product:`, dff.product)
        console.log(`- dff[${index}] productSamples:`, dff.productSamples)
      })
    }
    
    const response = await fetch(gpoApiUrl, {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
        'Sgstoken': mainStore.sgsToken,
        'Productlinecode': submitData.productLineCode
      },
      body: JSON.stringify(requestData)
    })
    
    const result = await response.json()
    
    console.log('SGS API响应:', result)
    
    // SGS GPO API响应格式处理
    if (result.success || result.status === 200) {
      message.success('DFF数据更新成功！')
      console.log('DFF更新结果:', result)
      
      // 可选：更新成功后重置表单或返回第一步
      // resetForm()
    } else {
      const errorMessage = result.message || 'DFF数据更新失败'
      message.error(`${errorMessage} (状态码: ${result.status || response.status})`)
      console.error('DFF更新失败:', { 
        httpStatus: response.status, 
        apiStatus: result.status,
        result 
      })
    }
  } catch (error) {
    console.error('DFF API调用失败:', error)
    message.error('DFF API调用失败: ' + error.message)
  } finally {
    dffTestLoading.value = false
  }
}

// 重置表单
const resetForm = () => {
  basicInfo.value = {
    objectNo: '',
    objectType: 'order',
    productLineCode: ''
  }
  availableFields.value = {
    customerFields: {},
    serviceFields: {},
    dffFields: {},
    dffList: []
  }
  fieldValues.value = {
    customerFields: {},
    serviceFields: {},
    dffFields: {},
    dffList: []
  }
  fieldsLoaded.value = false
  currentStep.value = 0
  dffTestFormRef.value?.restoreValidation()
}

// 上一步
const prevStep = () => {
  if (currentStep.value > 0) {
    currentStep.value--
  }
}

// 下一步
const nextStep = async () => {
  if (currentStep.value === 0) {
    // 验证基本信息后进入获取字段步骤
    try {
      await dffTestFormRef.value?.validate()
      currentStep.value = 1
    } catch (error) {
      // 验证失败，不进行下一步
    }
  } else if (currentStep.value === 1) {
    // 获取字段
    await fetchAvailableFields()
  }
}

// 添加DFF项目
const addDffItem = () => {
  fieldValues.value.dffList.push({
    languageId: 1,
    product: {
      productDescription: '',
      lotNo: '',
      refCode1: ''
    },
    productSamples: [
      {
        sampleID: '',
        otherSampleInformation: '',
        productDescription: ''
      }
    ]
  })
}

// 删除DFF项目
const removeDffItem = (index) => {
  if (fieldValues.value.dffList.length > 1) {
    fieldValues.value.dffList.splice(index, 1)
  }
}

// 添加样品
const addSample = (dffIndex) => {
  fieldValues.value.dffList[dffIndex].productSamples.push({
    sampleID: '',
    otherSampleInformation: '',
    productDescription: ''
  })
}

// 删除样品
const removeSample = (dffIndex, sampleIndex) => {
  if (fieldValues.value.dffList[dffIndex].productSamples.length > 1) {
    fieldValues.value.dffList[dffIndex].productSamples.splice(sampleIndex, 1)
  }
}



// 计算属性：是否有可填写的字段
const hasFieldsToFill = computed(() => {
  return Object.keys(availableFields.value.customerFields || {}).length > 0 ||
         Object.keys(availableFields.value.serviceFields || {}).length > 0 ||
         Object.keys(availableFields.value.dffFields || {}).length > 0 ||
         (availableFields.value.dffList && availableFields.value.dffList.length > 0)
})



// 填写进度计算
const filledFieldsCount = computed(() => {
  let count = 0
  
  // 统计已填写的 Customer 字段
  Object.values(fieldValues.value.customerFields).forEach(value => {
    if (value && value.trim()) count++
  })
  
  // 统计已填写的 Service 字段
  Object.values(fieldValues.value.serviceFields).forEach(value => {
    if (value && value.trim()) count++
  })
  
  // 统计已填写的 DFF 字段
  Object.values(fieldValues.value.dffFields).forEach(value => {
    if (value && value.trim()) count++
  })
  
  // 统计 DFF 数据结构中已填写的字段
  fieldValues.value.dffList.forEach(item => {
    if (item.languageId) count++
    if (item.product.productDescription && item.product.productDescription.trim()) count++
    if (item.product.lotNo && item.product.lotNo.trim()) count++
    if (item.product.refCode1 && item.product.refCode1.trim()) count++
    
    item.productSamples.forEach(sample => {
      if (sample.sampleID && sample.sampleID.trim()) count++
      if (sample.otherSampleInformation && sample.otherSampleInformation.trim()) count++
      if (sample.productDescription && sample.productDescription.trim()) count++
    })
  })
  
  return count
})

const totalFieldsCount = computed(() => {
  let count = 0
  
  // Customer 字段数量
  count += Object.keys(availableFields.value.customerFields || {}).length
  
  // Service 字段数量
  count += Object.keys(availableFields.value.serviceFields || {}).length
  
  // DFF 字段数量
  count += Object.keys(availableFields.value.dffFields || {}).length
  
  // DFF 数据结构字段数量
  fieldValues.value.dffList.forEach(item => {
    count += 4 // languageId, productDescription, lotNo, refCode1
    count += item.productSamples.length * 3 // 每个样品3个字段
  })
  
  return count
})

</script>

<template>
  <div class="dff-test-page">
    <n-card title="DFF API测试" class="mb-4">
      <!-- 步骤指示器 -->
      <n-steps :current="currentStep" class="mb-6">
        <n-step 
          v-for="(step, index) in steps" 
          :key="index"
          :title="step.title"
          :description="step.description"
        />
      </n-steps>

      <!-- 步骤1: 基本信息输入 -->
      <div v-if="currentStep === 0">
        <n-form 
          ref="dffTestFormRef"
          :model="basicInfo" 
          :rules="basicInfoRules"
          label-placement="left" 
          label-width="200px"
        >
          <n-form-item label="Object No" path="objectNo" required>
            <n-input 
              v-model:value="basicInfo.objectNo" 
              placeholder="请输入Object No" 
              clearable
            />
          </n-form-item>
          
          <n-form-item label="Object Type" path="objectType" required>
            <n-select 
              v-model:value="basicInfo.objectType" 
              :options="[
                { label: 'Order', value: 'order' },
                { label: 'Enquiry', value: 'enquiry' }
              ]"
              placeholder="请选择Object Type"
            />
          </n-form-item>
          
          <n-form-item label="Product Line Code" path="productLineCode" required>
            <n-input 
              v-model:value="basicInfo.productLineCode" 
              placeholder="请输入Product Line Code" 
              clearable
            />
          </n-form-item>

          <n-form-item>
            <n-space>
              <n-button type="primary" @click="nextStep">
                下一步
              </n-button>
              <n-button @click="resetForm">
                重置
              </n-button>
            </n-space>
          </n-form-item>
        </n-form>
      </div>

      <!-- 步骤2: 获取字段 -->
      <div v-if="currentStep === 1">
        <n-alert type="info" title="准备获取字段" class="mb-4">
          <div>
            <p><strong>Object No:</strong> {{ basicInfo.objectNo }}</p>
            <p><strong>Object Type:</strong> {{ basicInfo.objectType }}</p>
            <p><strong>Product Line Code:</strong> {{ basicInfo.productLineCode }}</p>
          </div>
          <div class="mt-3">
            <p>点击"获取字段"按钮将根据上述信息查询可更新的DFF字段。</p>
          </div>
        </n-alert>

        <n-space>
          <n-button @click="prevStep">
            上一步
          </n-button>
          <n-button 
            type="primary" 
            :loading="fieldsLoading" 
            @click="fetchAvailableFields"
          >
            获取字段
          </n-button>
          <n-button @click="resetForm">
            重置
          </n-button>
        </n-space>
      </div>

      <!-- 步骤3: 填写字段 -->
      <div v-if="currentStep === 2 && fieldsLoaded">
        <n-alert type="success" title="字段获取成功" class="mb-4">
          <div>
            <p>请填写需要更新的字段值，留空的字段将不会被更新。</p>
            <p><strong>进度：</strong>已填写 {{ filledFieldsCount }} / {{ totalFieldsCount }} 个字段</p>
          </div>
        </n-alert>



        <n-form label-placement="left" label-width="250px">
          <!-- Customer字段 -->
          <n-collapse>
            <n-collapse-item title="Customer字段" name="customer">
              <template #header-extra>
                <n-tag size="small" type="info">
                  {{ Object.keys(availableFields.customerFields || {}).length }} 个字段
                </n-tag>
              </template>
              <n-form-item 
                v-for="(value, key) in availableFields.customerFields || {}" 
                :key="key" 
                :label="key"
              >
                <n-input 
                  v-model:value="fieldValues.customerFields[key]" 
                  :placeholder="`请输入${key}`" 
                  clearable
                />
              </n-form-item>
            </n-collapse-item>

            <!-- Service字段 -->
            <n-collapse-item title="Service字段" name="service">
              <template #header-extra>
                <n-tag size="small" type="info">
                  {{ Object.keys(availableFields.serviceFields || {}).length }} 个字段
                </n-tag>
              </template>
              <n-form-item 
                v-for="(value, key) in availableFields.serviceFields || {}" 
                :key="key" 
                :label="key"
                :class="['Invoice Deliver To', 'SoftCopy Deliver To', 'Return Sample To'].includes(key) ? 'required-field' : ''"
              >
                <n-input 
                  v-model:value="fieldValues.serviceFields[key]" 
                  :placeholder="['Invoice Deliver To', 'SoftCopy Deliver To', 'Return Sample To'].includes(key) ? `请输入${key}（必填）` : `请输入${key}`" 
                  clearable
                  :class="['Invoice Deliver To', 'SoftCopy Deliver To', 'Return Sample To'].includes(key) ? 'required-input' : ''"
                />
              </n-form-item>
            </n-collapse-item>

            <!-- DFF字段 -->
            <n-collapse-item 
              v-if="Object.keys(fieldValues.dffFields).length > 0"
              title="DFF字段" 
              name="dff"
            >
              <template #header-extra>
                <n-tag size="small" type="info">
                  {{ Object.keys(availableFields.dffFields || {}).length }} 个字段
                </n-tag>
              </template>
              <n-form-item 
                v-for="(value, key) in availableFields.dffFields || {}" 
                :key="key" 
                :label="key"
              >
                <n-input 
                  v-model:value="fieldValues.dffFields[key]" 
                  :placeholder="`请输入${key}`" 
                  clearable
                />
              </n-form-item>
            </n-collapse-item>

            <!-- DFF数据结构 -->
            <n-collapse-item title="DFF数据结构" name="dffList">
              <template #header-extra>
                <n-tag size="small" type="info">
                  {{ fieldValues.dffList.length }} 个项目
                </n-tag>
              </template>
              
              <div v-for="(item, index) in fieldValues.dffList" :key="index" class="mb-4">
                <n-card :title="`DFF项目 ${index + 1}`" size="small">
                  <template #header-extra>
                    <n-space>
                      <n-button 
                        size="small" 
                        @click="addDffItem"
                        type="primary"
                        secondary
                      >
                        添加项目
                      </n-button>
                      <n-button 
                        size="small" 
                        @click="removeDffItem(index)"
                        type="error"
                        secondary
                        :disabled="fieldValues.dffList.length <= 1"
                      >
                        删除项目
                      </n-button>
                    </n-space>
                  </template>

                  <n-form-item label="Language ID" class="required-field">
                    <n-input-number 
                      v-model:value="item.languageId" 
                      :min="1" 
                      placeholder="语言ID（必填）"
                      class="required-input"
                    />
                  </n-form-item>
                  
                  <n-form-item label="Product Description">
                    <n-input 
                      v-model:value="item.product.productDescription" 
                      placeholder="请输入产品描述" 
                      clearable
                    />
                  </n-form-item>
                  
                  <n-form-item label="Lot No">
                    <n-input 
                      v-model:value="item.product.lotNo" 
                      placeholder="请输入批次号" 
                      clearable
                    />
                  </n-form-item>
                  
                  <n-form-item label="Ref Code 1">
                    <n-input 
                      v-model:value="item.product.refCode1" 
                      placeholder="请输入参考代码1" 
                      clearable
                    />
                  </n-form-item>

                  <!-- Product Samples -->
                  <n-divider title-placement="left">Product Samples</n-divider>
                  <div v-for="(sample, sampleIndex) in item.productSamples" :key="sampleIndex" class="mb-3">
                    <n-card :title="`样品 ${sampleIndex + 1}`" size="small">
                      <template #header-extra>
                        <n-space>
                          <n-button 
                            size="small" 
                            @click="addSample(index)"
                            type="primary"
                            secondary
                          >
                            添加样品
                          </n-button>
                          <n-button 
                            size="small" 
                            @click="removeSample(index, sampleIndex)"
                            type="error"
                            secondary
                            :disabled="item.productSamples.length <= 1"
                          >
                            删除样品
                          </n-button>
                        </n-space>
                      </template>

                      <n-form-item label="Sample ID" class="required-field">
                        <n-input 
                          v-model:value="sample.sampleID" 
                          placeholder="请输入样品ID（必填）" 
                          clearable
                          class="required-input"
                        />
                      </n-form-item>
                      
                      <n-form-item label="Other Sample Information">
                        <n-input 
                          v-model:value="sample.otherSampleInformation" 
                          placeholder="请输入其他样品信息" 
                          clearable
                        />
                      </n-form-item>
                      
                      <n-form-item label="Product Description">
                        <n-input 
                          v-model:value="sample.productDescription" 
                          placeholder="请输入产品描述" 
                          clearable
                        />
                      </n-form-item>
                    </n-card>
                  </div>
                </n-card>
              </div>
            </n-collapse-item>
          </n-collapse>

          <!-- 操作按钮 -->
          <n-form-item class="mt-8">
            <n-space>
              <n-button @click="prevStep">
                上一步
              </n-button>
              <n-button 
                type="primary" 
                :loading="dffTestLoading" 
                @click="submitDffUpdate"
                :disabled="!hasFieldsToFill || filledFieldsCount === 0"
              >
                提交更新 ({{ filledFieldsCount }} 个字段)
              </n-button>
              <n-button @click="resetForm">
                重置
              </n-button>
            </n-space>
          </n-form-item>
        </n-form>
      </div>
    </n-card>
  </div>
</template>

<style lang="stylus" scoped>
.dff-test-page
  .n-card
    min-height: 400px
    
  .n-steps
    margin-bottom: 24px
    
  .mb-3
    margin-bottom: 12px
    
  .mb-4
    margin-bottom: 16px
    
  .mb-6
    margin-bottom: 24px
    
  .mt-3
    margin-top: 12px
    
  .mt-8
    margin-top: 32px
    padding-top: 16px
    border-top: 1px solid #f0f0f0

/* 必填项样式 - 使用更强的选择器 */
.required-field
  .n-form-item-label
    color: #d03050 !important
    font-weight: 600 !important
    
    &::after
      content: " *"
      color: #d03050 !important
      font-weight: bold !important

/* 输入框边框样式 - 使用更强的选择器 */
.required-input
  border: 2px solid #d03050 !important
  
  .n-input
    .n-input-wrapper
      border-color: #d03050 !important
      border-width: 2px !important
      
    &:focus-within .n-input-wrapper
      border-color: #d03050 !important
      box-shadow: 0 0 0 2px rgba(208, 48, 80, 0.2) !important
      
  .n-input-number
    border-color: #d03050 !important
    border-width: 2px !important
    
    .n-input-number-input .n-input-wrapper
      border-color: #d03050 !important
      border-width: 2px !important
      
    &:focus-within .n-input-number-input .n-input-wrapper
      border-color: #d03050 !important
      box-shadow: 0 0 0 2px rgba(208, 48, 80, 0.2) !important
</style>